<template>
  <Upload
    name="file"
    listType="picture-card"
    :class="`avatar-uploader ${className}`"
    :showUploadList="false"
    :beforeUpload="beforeUpload"
  >
    <div class="wrap">
      <div v-if="image != ''" class="modal-tip">
        <div class="modal-tip-operate">
          <a class="upload-del-btn del-icon">
            <Icon type="delete" @click.stop="removeFunc" />
          </a>
          <a class="upload-edit-btn">
            <Icon type="edit" />
          </a>
        </div>
      </div>
      <img class="img-item" v-if="image != ''" :src="image" alt="avatar" />
      <div v-else class="img-item">
        <a-progress v-if="imgLoading" :width="32" type="circle" :percent="percent"></a-progress>
        <Icon v-else type="plus" />
        <div v-if="imgLoading && typeof cancelUploadFunc === 'function'" class="ant-upload-text">
          <Icon type="close" :style="{ fontSize: '18px' }" @click.stop="handleCancelUpload" />
        </div>
        <div v-else class="ant-upload-text">上传</div>
      </div>
    </div>
  </Upload>
</template>

<script>
import { Upload, Icon, message } from 'ant-design-vue';
import { baseURL } from '@/config/api.config'
export default {
  name: 'UploadSingle',
  props: {
    limit: {
      type: Number,
      default: 10
    },
    uploadFunc: {
      type: Function,
      required: true
    },
    cancelUploadFunc: {
      type: Function,
      required: false,
      default: null
    },
    className: {
      type: String,
      required: false,
      default: ''
    }
  },
  components: {
    Icon,
    Upload
  },
  data() {
    return {
      image: '',
      imgLoading: false,
      percent: 0, //进度条
      file: null,
      UPLOAD_ADDRESS: baseURL //在index.js中配上传服务器地址
    };
  },
  methods: {
    beforeUpload(file) {
      const { limit, uploadFunc } = this;
      this.image = '';
      this.file = file;
      this.imgLoading = true;
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif';
      if (!isJpgOrPng) {
        this.imgLoading = false;
        message.error('只能上传JPG/PNG/JPEG/GIF格式文件!');
      }
      const isLt = file.size / 1024 / 1024 < limit;
      if (!isLt) {
        this.imgLoading = false;
        message.error(`图片需小于${limit}M!`);
      }
      if (isJpgOrPng && isLt) {
        uploadFunc(
          [file],
          (file, progressEvent) => {
            console.log('progess', file, progressEvent);
            if (progressEvent.lengthComputable) {
              const { loaded, total } = progressEvent;
              this.percent = parseInt(((loaded / total) * 100).toFixed(0));
            }
          },
          (file, res) => {
            const { data } = res;
            this.image = this.UPLOAD_ADDRESS + data[0];
            this.imgLoading = false;
            this.$emit('uploadCallback', this.image);
          },
          (file, err)=>{
            if(!err.selfCancel){
              console.log('err',err);
              this.imgLoading = false;
              this.image = ''
              message.error('上传失败')
            }
          }
        );
      }
    },
    handleCancelUpload() {
      if (this.imgLoading) {
        this.cancelUploadFunc(this.file.uid, () => {
          message.success('取消上传成功');
          this.image = '';
          this.imgLoading = false;
        });
      }
    },
    removeFunc() {
      this.image = '';
      this.$emit('removeCallback', this.image);
    },
    setImageUrl(url) {
      this.image = url ? url : '';
    },
    getImageUrl() {
      return this.image;
    }
  }
};
</script>

<style scoped>
.wrap {
  align-items: center;
  text-align: center;
  position: relative;
  display: flex;
  width: 100%;
  height: 100%;
}
.wrap .img-item {
  flex: 1;
  width: 100%;
}
.avatar-uploader .modal-tip {
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  display: none;
}
.avatar-uploader .modal-tip .modal-tip-operate {
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 10;
  white-space: nowrap;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: all 0.3s;
}
.ant-upload:hover .modal-tip {
  display: block;
}
.ant-upload:hover .modal-tip-operate {
  opacity: 1;
}
.ant-upload .modal-tip-operate i:hover {
  color: #fff;
}
.ant-upload .modal-tip-operate i {
  font-size: 18px;
  color: hsla(0, 0%, 100%, 0.85);
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.del-icon {
  margin-right: 10px;
}
</style>
